package com.itheima.thread.security.dem04;

public class SellTicket implements Runnable {

    private static int tickets = 100;
    private Object object = new Object();

    private int count = 0;

    @Override
    public void run() {
        while (true){
            if (count % 2 == 0) {
//                synchronized (object) {                  //对应同步代码块
                synchronized (this) {                  //对应无static的同步方法
//                synchronized (SellTicket.class) {        //对应有static的同步方法
                    if (tickets > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                        tickets--;
                    }
                }
            } else {
               sellTickets();
            }
            count++;
        }
    }

    public static synchronized void sellTickets(){

        if (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
            tickets--;
        }

    }

//    public synchronized void sellTickets(){
//
//            if (tickets > 0) {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
//                tickets--;
//            }
//
//    }
}
